package net.angrynut.web.handler.controller;

import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.ImmutableMap;

import net.angrynut.web.model.entity.User;
import net.angrynut.web.model.validator.UserValidator;

/**
 * Spring 校验机制演示。找了个
 * <a href="http://blog.csdn.net/walkerjong/article/details/7210727">blog</a>。
 *
 */
@RestController
public class DemoValidatorController {

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setValidator(new UserValidator());
	}

	@PostMapping("/demo/validator")
	public Object validator(@RequestBody @Validated User user, BindingResult br) {
		if (br.hasErrors()) {
			return br.getFieldErrors();
		}
		return ImmutableMap.of("resule", "OK");
	}
}
